package com.ncmem.up6.utils;

import com.ncmem.up6.store.FileBlockReader;

import java.io.IOException;
import java.io.OutputStream;

public class WebWriter {
    public int cacheSize = 1048576;//1MB，默认内存块大小

    /// <summary>
    ///
    /// </summary>
    /// <param name="fr"></param>
    /// <param name="hr"></param>
    /// <param name="pathSvr"></param>
    /// <param name="blockSize">需要下载的大小</param>
    public boolean write(FileBlockReader fr, OutputStream os, String pathSvr, long offset, int blockSize) throws IOException {
        boolean ret=true;
        // 总共需要下载的长度
        int dataToRead = blockSize;
        //每次读1MB，然后传给终端
        int buf_size = Math.min(this.cacheSize, blockSize);
        byte[] buffer = null;
        int length=0;//当前读取到的数据长度

        try {
            while (dataToRead > 0 && ret)
            {
                // 读取数据
                buffer = fr.read(pathSvr, offset, buf_size);
                //写入Web
                os.write(buffer,0,buffer.length);
                os.flush();

                length = buffer.length;
                dataToRead -= length;
                offset+=length;//
                buf_size = dataToRead < buf_size ? dataToRead : buf_size;

                //读取错误
                if(buffer.length==0) ret = false;
            }
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException("read data error");
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("read data error");
        }
        return ret;
    }
}
